<template>
  <div v-permission="['sc:sale:return:check']">
    <page-wrapper content-full-height fixed-height>
      <!-- 搜索表单 -->
      <div class="search-wrapper">
        <j-form layout="inline">
          <j-form-item label="流程类型">
            <a-select v-model:value="searchFormData.status" allow-clear placeholder="请选择状态">
              <a-select-option value="PURCHASE_ORDER">采购订单</a-select-option>
              <a-select-option value="PURCHASE_RECEIVE">采购收货</a-select-option>
              <a-select-option value="PURCHASE_RETURN">采购退货</a-select-option>
              <a-select-option value="RETAIL_OUT">零售出库</a-select-option>
              <a-select-option value="RETAIL_RETURN">零售退货</a-select-option>
              <a-select-option value="SALE_ORDER">销售订单</a-select-option>
              <a-select-option value="SALE_OUT">销售出库</a-select-option>
              <a-select-option value="SALE_RETURN">销售退货</a-select-option>
              <a-select-option value="STOCK_ADJUST">库存调整</a-select-option>
              <a-select-option value="STOCK_TAKE">盘点单管理</a-select-option>
              <a-select-option value="STOCK_TRANSFER">仓库调拨</a-select-option>
              <a-select-option value="SUPPLIER_FEE">供应商费用</a-select-option>
              <a-select-option value="SUPPLIER_PREPAY">供应商预付款</a-select-option>
              <a-select-option value="SUPPLIER_CHECK">供应商对账</a-select-option>
              <a-select-option value="SUPPLIER_SETTLE">供应商结算</a-select-option>
              <a-select-option value="CUSTOMER_FEE">客户费用</a-select-option>
              <a-select-option value="CUSTOMER_PREPAY">客户预收款</a-select-option>
              <a-select-option value="CUSTOMER_CHECK">客户对账</a-select-option>
              <a-select-option value="CUSTOMER_SETTLE">客户结算</a-select-option>
            </a-select>
          </j-form-item>
          <div class="action-btns">
            <a-space>
              <a-button type="primary" @click="search" :icon="h(SearchOutlined)">查询</a-button>
            </a-space>
          </div>
        </j-form>
      </div>

      <!-- 数据表格 -->
      <vxe-grid id="Delivery" ref="grid" resizable show-overflow highlight-hover-row keep-source row-id="id"
        :columns="tableColumn" :toolbar-config="toolbarConfig" :proxy-config="proxyConfig" :pager-config="{}"
        :custom-config="{}">
        <!-- 工具栏 -->
        <template #toolbar_buttons>
          <a-space>
            <a-button type="primary" :icon="h(PlusOutlined)" @click="handleAdd">新增</a-button>
            <a-button type="primary" danger :icon="h(DeleteOutlined)" @click="handleBatchDelete">删除</a-button>
          </a-space>
        </template>

        <!-- 状态列 -->
        <template #status_default="{ row }">
          <a-tag :color="getStatusColor(row.status)">
            {{ getStatusText(row.status) }}
          </a-tag>
        </template>
        <!-- 流程类型列 -->
        <template #code_default="{ row }">
          {{ PROCESS_TYPE_MAP[row.code] || row.code }}
        </template>
        <!-- 操作列 -->
        <template #action_default="{ row }">
          <table-action :actions="createActions(row)" />
        </template>
      </vxe-grid>
      <!-- 验收弹窗 -->
      <add-audits ref="addAuditsRef" @success="search" />
    </page-wrapper>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, h } from 'vue';
import { SearchOutlined, ReloadOutlined, PlusOutlined, DeleteOutlined } from '@ant-design/icons-vue';
import AddAudits from './components/AddAudits.vue';
import { message } from 'ant-design-vue';

export default defineComponent({
  name: 'SaleReturnCheck',
  components: {
    SearchOutlined,
    ReloadOutlined,
    PlusOutlined,
    DeleteOutlined,
    AddAudits,
  },
  setup() {
    const grid = ref();
    const addAuditsRef = ref();
    const searchFormData = ref({
      status: undefined,
    });

    // 表格列配置
    const tableColumn = [
      { type: 'checkbox', width: 50, fixed: 'left' },
      { field: 'action', title: '操作', width: 120, slots: { default: 'action_default' }, fixed: 'left' },
      {
        field: 'code',
        title: '流程类型',
        width: 180,
        slots: { default: 'code_default' }
      },
      { field: 'customerName', title: '发起人', width: 200 },
      { field: 'totalAmount', title: '当前审核人', width: 120 },
      { field: 'createTime', title: '创建时间' },
    ];

    // 工具栏配置
    const toolbarConfig = {
      slots: {
        buttons: 'toolbar_buttons',
      },
      refresh: true,
      export: true,
      print: true,
      zoom: true,
      custom: true,
    };

    // 代理配置
    const proxyConfig = {
      ajax: {
        query: ({ page, sorts, filters }) => {
          // 模拟API返回数据
          return Promise.resolve({
            code: 200,
            msg: 'success',
            data: {
              records: [
                {
                  id: '1',
                  code: 'PURCHASE_ORDER',
                  customerName: '李四',
                  totalAmount: 'C001',
                  createTime: '2024-01-01 10:00:00',
                }
              ],
              total: 2
            },
          })
        },
      },
      props: {
        result: 'data.records',
        total: 'data.total',
      },
    };

    // 流程类型映射
    const PROCESS_TYPE_MAP: Record<string, string> = {
      PURCHASE_ORDER: '采购订单',
      PURCHASE_RECEIVE: '采购收货',
      PURCHASE_RETURN: '采购退货',
      RETAIL_OUT: '零售出库',
      RETAIL_RETURN: '零售退货',
      SALE_ORDER: '销售订单',
      SALE_OUT: '销售出库',
      SALE_RETURN: '销售退货',
      STOCK_ADJUST: '库存调整',
      STOCK_TAKE: '盘点单管理',
      STOCK_TRANSFER: '仓库调拨',
      SUPPLIER_FEE: '供应商费用',
      SUPPLIER_PREPAY: '供应商预付款',
      SUPPLIER_CHECK: '供应商对账',
      SUPPLIER_SETTLE: '供应商结算',
      CUSTOMER_FEE: '客户费用',
      CUSTOMER_PREPAY: '客户预收款',
      CUSTOMER_CHECK: '客户对账',
      CUSTOMER_SETTLE: '客户结算',
    };
    // 获取状态颜色
    const getStatusColor = (status: string) => {
      const colorMap: Record<string, string> = {
        CREATED: 'warning',
        CHECKED: 'success',
        REJECTED: 'error',
      };
      return colorMap[status] || 'default';
    };

    // 获取状态文本
    const getStatusText = (status: string) => {
      const textMap: Record<string, string> = {
        CREATED: '待验收',
        CHECKED: '已验收',
        REJECTED: '已拒收',
      };
      return textMap[status] || '未知';
    };

    // 创建操作按钮
    const createActions = (row: any) => {
      const actions = [];
      actions.push({
        label: '审核',
        onClick: () => addAuditsRef.value?.openDetail(row),
      });

      return actions;
    };

    // // 处理拒收
    // const handleReject = async (row: any) => {
    //   try {
    //     search();
    //   } catch (error) {
    //     console.error('拒收失败:', error);
    //   }
    // };

    // 查询
    const search = () => {
      grid.value?.commitProxy('query');
    };

    // 重置查询
    const resetSearch = () => {
      searchFormData.value = {
        status: undefined,
      };
      search();
    };

    // 处理新增
    const handleAdd = () => {
      addAuditsRef.value?.openAdd();
    };

    // 处理批量删除
    const handleBatchDelete = async () => {
      const selections = grid.value?.getCheckboxRecords();
      if (!selections || selections.length === 0) {
        message.warning('请选择要删除的数据');
        return;
      }

      try {
        // await saleReturnApi.batchDelete(selections.map(item => item.id));
        message.success('删除成功');
        search();
      } catch (error) {
        console.error('删除失败:', error);
      }
    };

    return {
      h,
      SearchOutlined,
      ReloadOutlined,
      PlusOutlined,
      DeleteOutlined,
      AddAudits,
      grid,
      addAuditsRef,
      searchFormData,
      tableColumn,
      toolbarConfig,
      proxyConfig,
      getStatusColor,
      getStatusText,
      createActions,
      search,
      resetSearch,
      handleAdd,
      handleBatchDelete,
      PROCESS_TYPE_MAP
    };
  },
});
</script>

<style lang="less" scoped>
.search-wrapper {
  position: relative;
  background-color: #fff;
  padding: 16px;
  margin-bottom: 16px;
  border-radius: 2px;

  :deep(.ant-form) {
    display: flex;
    flex-wrap: wrap;
    gap: 16px;

    .ant-form-item {
      margin-bottom: 0;

      .ant-select {
        width: 300px;
      }
    }
  }

  .action-btns {
    display: flex;
    align-items: center;
    margin-left: 8px;
  }
}
</style>
